<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;

// 引入TP的数据库类
use think\Db;

/**
 * 回收站
 *
 * @icon fa fa-circle-o
 */
class Recyclebin extends Backend
{

    /**
     * Business模型对象
     * @var \app\common\model\Business\Business
     */
    protected $model = null;

    // 当前是否为关联查询
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Business.Business');
        $this->Visitmodel = model('Business.Visit');
        $this->Sourcemodel = model('Business.Source');
        $this->Adminmodel = model('Business.Admin');
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("dealList", $this->model->getDealList());
    }

    /**
     * 回收站
     */
    public function index()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                require $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 查询总数
            $total = $this->model
                ->onlyTrashed()  // 仅查询软删除的数据
                ->where($where)
                ->count();

            // 查询数据
            $list = $this->model
                ->onlyTrashed() // 仅查询软删除的数据
                ->with(['source', 'visit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 真实删除
     */
    public function destroy($ids = 0)
    {
        // 查询删除的数据
        $rows = $this->model->onlyTrashed()->select($ids);

        if (!$rows) {
            $this->error('暂无删除的数据');
            exit;
        }

        // 先将数据删除了
        $result = $this->model->destroy($ids, true);

        if ($result === FALSE) {
            $this->error('删除失败');
            exit;
        } else {
            $this->success();
            exit;
        }
    }

    /**
     * 还原 - 更新 - deletetime 改为 NULL
     */
    public function restore($ids = 0)
    {
        // 执行更新语句
        $result = Db::name('business')->where(['id' => ['in', $ids]])->update(['deletetime' => NULL]);

        // 判断是否还原成功
        if ($result) {
            $this->success();
            exit;
        } else {
            $this->error(__('还原失败'));
            exit;
        }
    }
}
